<?php
/**
 * 生成第一次的系统密码12位
 */
apf_require_controller("Abstract");
apf_require_class("Const_Tip");
apf_require_class("Util_Tools");
apf_require_class("Security_Api_Crypt_key");
apf_require_class("Bll_Flow_UserSecurityKey");

class Flow_InitKeyController extends AbstractController {

    public function handle_request() {
        $init_enable = $this->_check_init_enable();
        if(!$init_enable) {
            $this->show_tips('ERROR_AUTH');
        }
        $is_admin = $this->check_role_auth();
        if(!$is_admin) {
            $this->show_tips('ERROR_AUTH');
        }
        $data = array();
        $params = $this->request->get_parameters();
        if($this->request->is_post_method ()) {
                switch($params['step']) {
                    case 1:
                        $data['msg'] = Util_Tools::make_rand_key(12);
                        break;
                    case 2:
                        $error = $this->_check_params($params);
                        if(empty($error)){
                            $rs = $this->_create_user_security_key($params);
                            if($rs) {
                                $data['msg'] = "系统密文创建成功！";
                            }else {
                                $data['error'] = "系统密文创建失败！";
                            }
                        }else {
                            $data['error'] = $error['error'];
                        }
                        break;
                }
        }
        $this->request->set_attribute('params',$params);
        $this->request->set_attribute('data', $data);
        return 'Flow_InitKey';
    }

    private function _check_params($params) {
        if(empty($params['systemcode']) || empty($params['perponcode'])) {
            return array('error'=>"数据不能为空！");
        }
        return array();
    }

    private function _create_user_security_key($params) {

        $system_code = $params['systemcode'];
        $perpon_code = $params['perponcode'];
        $security_miwen = Security_Api_Crypt_key::get_instance()->encrypt($system_code, $perpon_code);
        return $this->_create_security_miwen($this->user_info,$security_miwen);
    }

    /**
     * 创建用户安全密文
     * @param unknown_type $user_id
     */
    private function _create_security_miwen($user_info,$security_miwen) {
        $bll_key = new Bll_Flow_UserSecurityKey();
        return $bll_key->set_user_miwen(array('user_id'=>$user_info['user_id'],'user_name'=>$user_info['user_name'],'user_code'=>$user_info['user_code']),
                $security_miwen);
    }

    /**
     * check 是否有初始化的权限
     * @return boolean
     */
    private function _check_init_enable() {
        $bll_key = new Bll_Flow_UserSecurityKey();
        return $bll_key->check_init_enable();
    }

}